﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using SimpleNotify.Service.Contracts;
using System.IO;

namespace SimpleNotify.Service
{
    [ServiceBehavior(
        InstanceContextMode = InstanceContextMode.Single,
        ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class Service : IService
    {
        SubscriptionManager _sm = null;
        Logger _logger = null;

        public Service()
        {
            _logger = new Logger("SimpleNotify.Service.log");
            _sm = new SubscriptionManager(_logger);
        }

        public bool Subscribe(string machineName)
        {
            bool retValue = false;           
            INotifyCallbackContract callerProxy = OperationContext.Current.GetCallbackChannel<INotifyCallbackContract>();
            _sm.UpdateSubscription(machineName, callerProxy);
            retValue = true;            
            return retValue;
        }

        public string[] GetSubscribers()
        {
            return _sm.GetSubscribers();
        }

        public PushResult PushMessageToClient(string clientToNotify, string title, string text, NotificationType type, string data)
        {
            PushResult result = _sm.NotifySubscriber(title, text, clientToNotify, type, data);
            return result;
        }

        public PushResult[] PushMessageToMany(string[] clientsToNofity, string title, string text, NotificationType type, string data)
        {
            List<PushResult> results = new List<PushResult>();
            foreach (var client in clientsToNofity)
            {
                results.Add(_sm.NotifySubscriber(title, text, client, type, data));
            }
            return results.ToArray();
        }
    }
}
